package com.easyExcel.handler;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

public class CustomMergeStrategy implements CellWriteHandler {

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {

    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {

    }
    /** 合并列名*/
    private final List<String> mergeColumnNames;
    /**构造函数 */
    public CustomMergeStrategy(List<String> mergeColumnNames){this.mergeColumnNames =mergeColumnNames;}


    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        //表头不做处理
        if(isHead){
            return;
        }
        //校验：如果当前是第一行，则不处理
        if(relativeRowIndex == 0){
            return;
        }

        //校验：如果当前列名不在合并列名列表中，则不处理
        if(!this.mergeColumnNames.contains(head.getFieldName())){
            return;
        }


        //获取：当前表格、当前行下标、上一行下标、上一行对象、上一列对象
        Sheet sheet = cell.getSheet();
        int rowIndexCurrent = cell.getRowIndex();
        int rowIndexPrevous = rowIndexCurrent - 1;

        Row rowPrev = sheet.getRow(rowIndexPrevous);
        Cell cellPrev = rowPrev.getCell(cell.getColumnIndex());
        Cell prevRowFirstColumn=rowPrev.getCell(0); //当前行上一行第一列的单元格
        String prevRowFirstColumnValue= prevRowFirstColumn.getStringCellValue(); //当前行上一行第一列的单元格值

        Row currentRow = sheet.getRow(rowIndexCurrent);//当前行
        Cell currentRowFirstColumn=currentRow.getCell(0);//当前行第一列的单元格
        String currentRowFirstColumnValue= currentRowFirstColumn.getStringCellValue();//当前行第一列的单元格值

        //获取单元格值、上一个单元值
        Object cellValueCurrent = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
        Object cellValuePrev = cellPrev.getCellTypeEnum() == CellType.STRING ? cellPrev.getStringCellValue() : cellPrev.getNumericCellValue();

            //校验：如果当前单元格和上一个不相等，不处理
            if (!cellValueCurrent.equals(cellValuePrev)){
                return;
            }
            //控制以特定某列为一组进行合并
            if(!prevRowFirstColumnValue.equals(currentRowFirstColumnValue)){
                return;
            }
            //获取已有策略
            List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
            boolean merged = false;

            for (int i = 0; i < mergedRegions.size(); i++) {
                CellRangeAddress cellRangeAddress = mergedRegions.get(i);

                if (cellRangeAddress.isInRange(rowIndexPrevous, cell.getColumnIndex())) {
                    sheet.removeMergedRegion(i);//移除单元格
                    cellRangeAddress.setLastRow(rowIndexCurrent);//设置单元格的结束行
                    sheet.addMergedRegion(cellRangeAddress);//重新添加合并单元格
                    merged = true;
                    break;
                }
            }
            if (!merged) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(rowIndexPrevous, rowIndexCurrent, cell.getColumnIndex(), cell.getColumnIndex());
                sheet.addMergedRegion(cellRangeAddress);
            }
        }

}
